package com.ymttest.business.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.fenqile.api.pop.parameter.*;
import com.fenqile.api.pop.service.*;
import com.google.common.reflect.TypeToken;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.thirdpartysync.parameter.addProductBean;
import com.ymatou.iapi.thirdpartysync.service.addProductCall;
import com.ymt.base.BaseBean;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.thirdpartysync.fenqilebrand;
import com.ymttest.database.model.thirdpartysync.fenqilebrandExample;
import com.ymttest.database.model.thirdpartysync.fenqilecategory;
import com.ymttest.database.model.thirdpartysync.fenqilecategoryExample;
import com.ymttest.database.model.thirdpartysync.fenqileproduct;
import com.ymttest.database.model.thirdpartysync.fenqileproductExample;
import com.ymttest.database.model.thirdpartysync.fenqilesku;
import com.ymttest.database.model.thirdpartysync.fenqileskuExample;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.database.sqlwapper.thirdpartysync.thirdpartysyncWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class FQLOpenCallService {
	public static String KEY="3ccf28df785904dfad4d9409afc34c18";
	public static String PartnerId="PAI201910220000445";
	/**
	 * 调用fqlpop接口
	 * @param method
	 * @param fqlbean
	 * @return
	 * @throws Exception 
	 */
	public static String FenqilePopCall(String method,BaseBean fqlbean) throws Exception {
		FQLBaseParam FQLBaseParam=new FQLBaseParam();
		FenqilePopCall FenqilePopCall=new FenqilePopCall();
		FQLBaseParam=new FQLBaseParam();
		FQLBaseParam.setFormat("json");
		FQLBaseParam.setMethod(method);
		FQLBaseParam.setPartner_id(FQLOpenCallService.PartnerId);
		FQLBaseParam.setV("1.3");
		FQLBaseParam.setTimestamp(YMTDateUtil.getDate().getTime()/1000);
		TreeMap tm = new TreeMap();
		Map m1 = FormatUtil.beanToMap(FQLBaseParam);
		tm.putAll(m1);
		if(fqlbean!=null) {
			Map m2 = FormatUtil.beanToMap(fqlbean);
			tm.putAll(m2);
		}
		 TestDataManager.removeNullValue(tm);
		String fromatS = FormatUtil.mapToHttpString(tm, false);
		fromatS+="&partner_key="+FQLOpenCallService.KEY;
		String signmd5 = TestDataManager.getMD5(fromatS.getBytes());
		FQLBaseParam.setSign(signmd5);
		String opurlparam=FormatUtil.beanToHttpString(FQLBaseParam,false);
		FenqilePopCall=new FenqilePopCall(opurlparam);
		String postparam=FormatUtil.beanToHttpString(fqlbean,false);
		FenqilePopCall.setData(postparam);
		FenqilePopCall.callService();	
		return TestDataManager.unicodeStr2String(FenqilePopCall.getReturnData());
	}
	
	
	/**
	 * 调用fqlpop接口
	 * @param method
	 * @param fqlbean
	 * @return
	 * @throws Exception 
	 */
	public static List<Product> FenqilePopCallToObject(String method,BaseBean fqlbean) throws Exception {
		FQLBaseParam FQLBaseParam=new FQLBaseParam();
		FenqilePopCall FenqilePopCall=new FenqilePopCall();
		FQLBaseParam=new FQLBaseParam();
		FQLBaseParam.setFormat("json");
		FQLBaseParam.setMethod(method);
		FQLBaseParam.setPartner_id(FQLOpenCallService.PartnerId);
		FQLBaseParam.setV("1.3");
		FQLBaseParam.setTimestamp(YMTDateUtil.getDate().getTime()/1000);
		TreeMap tm = new TreeMap();
		Map m1 = FormatUtil.beanToMap(FQLBaseParam);
		tm.putAll(m1);
		if(fqlbean!=null) {
			Map m2 = FormatUtil.beanToMap(fqlbean);
			tm.putAll(m2);
		}
		 TestDataManager.removeNullValue(tm);
		String fromatS = FormatUtil.mapToHttpString(tm, false);
		fromatS+="&partner_key="+FQLOpenCallService.KEY;
		String signmd5 = TestDataManager.getMD5(fromatS.getBytes());
		FQLBaseParam.setSign(signmd5);
		String opurlparam=FormatUtil.beanToHttpString(FQLBaseParam,false);
		FenqilePopCall=new FenqilePopCall(opurlparam);
		String postparam=FormatUtil.beanToHttpString(fqlbean,false);
		FenqilePopCall.setData(postparam);
		FenqilePopCall.callService();	
		
		String sResults=FenqilePopCall.getJsonObject().get("sku_detail_get_response").getAsJsonObject().get("items").getAsJsonArray().toString();
		List<Product> FreezeProductResultList=(List<Product>) FormatUtil.GSONToObject(sResults, new TypeToken<List<Product>>(){}.getType());
		return FreezeProductResultList;
	}
	
	
	/**
	 * 调用fqlpop接口
	 * @param method
	 * @param fqlbean
	 * @return
	 * @throws Exception 
	 */
	public static List<FenqileSkuItems> FenqilePopCallToSKUObject(String method,BaseBean fqlbean) throws Exception {
		FQLBaseParam FQLBaseParam=new FQLBaseParam();
		FenqileSKUPopCall fenqileSKUPopCall = new FenqileSKUPopCall();
		FQLBaseParam=new FQLBaseParam();
		FQLBaseParam.setFormat("json");
		FQLBaseParam.setMethod(method);
		FQLBaseParam.setPartner_id(FQLOpenCallService.PartnerId);
		FQLBaseParam.setV("1.3");
		FQLBaseParam.setTimestamp(YMTDateUtil.getDate().getTime()/1000);
		TreeMap tm = new TreeMap();
		Map m1 = FormatUtil.beanToMap(FQLBaseParam);
		tm.putAll(m1);
		if(fqlbean!=null) {
			Map m2 = FormatUtil.beanToMap(fqlbean);
			tm.putAll(m2);
		}
		 TestDataManager.removeNullValue(tm);
		String fromatS = FormatUtil.mapToHttpString(tm, false);
		fromatS+="&partner_key="+FQLOpenCallService.KEY;
		String signmd5 = TestDataManager.getMD5(fromatS.getBytes());
		FQLBaseParam.setSign(signmd5);
		String opurlparam=FormatUtil.beanToHttpString(FQLBaseParam,false);
		fenqileSKUPopCall=new FenqileSKUPopCall(opurlparam);
		String postparam=FormatUtil.beanToHttpString(fqlbean,false);
		fenqileSKUPopCall.setData(postparam);
		fenqileSKUPopCall.callService();	
		
		String sResults=fenqileSKUPopCall.getJsonObject().get("sku_detail_get_response").getAsJsonObject().get("items").getAsJsonArray().toString();
		List<FenqileSkuItems> FreezeProductResultList=(List<FenqileSkuItems>) FormatUtil.GSONToObject(sResults, new TypeToken<List<FenqileSkuItems>>(){}.getType());
		return FreezeProductResultList;
	}
	
	/**
	 * 调用fqlpop接口
	 * @param method
	 * @param fqlbean
	 * @return
	 * @throws Exception 
	 */
	public static Product FenqilePopCallTodetail(String method,BaseBean fqlbean) throws Exception {
		FQLBaseParam FQLBaseParam=new FQLBaseParam();
		FenqilePopCall FenqilePopCall=new FenqilePopCall();
		FQLBaseParam=new FQLBaseParam();
		FQLBaseParam.setFormat("json");
		FQLBaseParam.setMethod(method);
		FQLBaseParam.setPartner_id(FQLOpenCallService.PartnerId);
		FQLBaseParam.setV("1.3");
		FQLBaseParam.setTimestamp(YMTDateUtil.getDate().getTime()/1000);
		TreeMap tm = new TreeMap();
		Map m1 = FormatUtil.beanToMap(FQLBaseParam);
		tm.putAll(m1);
		if(fqlbean!=null) {
			Map m2 = FormatUtil.beanToMap(fqlbean);
			tm.putAll(m2);
		}
		 TestDataManager.removeNullValue(tm);
		String fromatS = FormatUtil.mapToHttpString(tm, false);
		fromatS+="&partner_key="+FQLOpenCallService.KEY;
		String signmd5 = TestDataManager.getMD5(fromatS.getBytes());
		FQLBaseParam.setSign(signmd5);
		String opurlparam=FormatUtil.beanToHttpString(FQLBaseParam,false);
		FenqilePopCall=new FenqilePopCall(opurlparam);
		String postparam=FormatUtil.beanToHttpString(fqlbean,false);
		FenqilePopCall.setData(postparam);
		FenqilePopCall.callService();	
		
		String sResults=FenqilePopCall.getJsonObject().get("product_detail_get_response").getAsJsonObject().getAsJsonObject("product").toString();
		Product FreezeProductResultList=(Product) FormatUtil.GSONToObject(sResults,Product.class);
		System.out.println("aaaaaaaaaa"+sResults);
		System.out.println("bbbbbbbbbb"+FreezeProductResultList);
		return FreezeProductResultList;
	}
	
	public static Map<String, Object> getFenqiLeSku() throws Exception{

		addProductBean bean=new addProductBean();
		addProductCall call=new addProductCall();
		ProductsWapper mongoDB_productsWapper=new ProductsWapper();
		int sellerId = Integer.parseInt(EnvSetup.getData("autotest_seller1"));
		fenqileproduct product=new fenqileproduct();
		fenqileproductExample productExample=new fenqileproductExample();
		thirdpartysyncWapper syncWapper=new thirdpartysyncWapper(); 
		
		fenqilesku sku=new fenqilesku();
		fenqileskuExample skuExample=new fenqileskuExample();
		
		fenqilecategory category=new fenqilecategory();
		fenqilecategoryExample categoryExample=new fenqilecategoryExample();
		
		fenqilebrand brand=new fenqilebrand();
		fenqilebrandExample brandExample=new fenqilebrandExample();
		//创建商品
		AddSellerProductRequest addpro = ProductManagerCallServiceV2.initAddSellerProductRequest(sellerId);
		addpro.getProduct().getCatalogList().remove(0);
		//addpro.getProduct().setSecondCategoryId(768);
		addpro.getProduct().setThirdCategoryId(1003);
		addpro.getProduct().setBrandId(ProductManagerCallServiceV3.BrandId);
		addpro.getProduct().setProductName("型号");
		addpro.getProduct().getCatalogList().get(0).getPropertyList().get(0).setPropertyName("型号");
		
		String productId = ProductManagerCallServiceV2.addNewProduct(addpro).get("Data").getAsJsonObject().get("ProductId").getAsString();
		
		List<String> ids=new ArrayList();
		ids.add(productId);
		bean.setProductIdList(ids);
		call.setData(bean);
		//查询mongo
		int times=2000;
		do{
			Map<String,Object> p= mongoDB_productsWapper.getByProductId(productId);
			if(p.size()==0 )
			{
				Thread.sleep(times);
				times+=2000;
			}else break;
		}while(times<=10000);
		
		if(times>10000)
			Logger.comment("商品未同步到mongo,无法添加分期乐商品");
		else 
			call.callService();
		Thread.sleep(2000);
	
		//查询数据库fenqileproduct
		
		productExample.createCriteria().andActionEqualTo(0).andSyncStatusEqualTo(1).andYmtSaleStatusEqualTo(1).andYmtProductIdEqualTo(productId);
		List<fenqileproduct> prodcuts_DB=syncWapper.selectByExample(productExample);
		//查询数据库fenqilesku
		skuExample.createCriteria().andActionEqualTo(0).andSyncStatusEqualTo(1).andYmtProductIdEqualTo(productId);
		List<fenqilesku> skus_DB=syncWapper.selectByExample(skuExample);
		//查询数据库fenqilecategory
		categoryExample.createCriteria().andActionEqualTo(0).andYmtCategory3IdEqualTo(addpro.getProduct().getThirdCategoryId());
		List<fenqilecategory> categorys_DB=syncWapper.selectByExample(categoryExample);
		//查询数据库fenqilebrand
		brandExample.createCriteria().andActionEqualTo(0).andYmtBrandIdEqualTo(addpro.getProduct().getBrandId());
		List<fenqilebrand>  brands_DB=syncWapper.selectByExample(brandExample);
		int sTimes=0;
		do{
		 	 if(prodcuts_DB.size()==0 )
			 {
		 		 sTimes+=2000;
				 Thread.sleep(sTimes);
				 prodcuts_DB=syncWapper.selectByExample(productExample);
				 skus_DB=syncWapper.selectByExample(skuExample);
				 categorys_DB=syncWapper.selectByExample(categoryExample);
				 brands_DB=syncWapper.selectByExample(brandExample);
				 Logger.comment("查询数据库休眠的时间："+sTimes);
				 if(prodcuts_DB.size()==0) continue;
			 }else	 break;
	    }while(sTimes<=10000);
		Product searchFenqileSync = null;
		if(sTimes>10000)
			Logger.comment("商品同步到分期乐异常");
		else {
			  searchFenqileSync = ThirdpartysyncCallService.searchFenqileSync(prodcuts_DB.get(0).getFqlProductId());
		}
		Logger.comment("prodcuts_DB:"+prodcuts_DB.size());
		Logger.comment("skus_DB:"+skus_DB.size());
		Logger.comment("categorys_DB:"+categorys_DB.size());
		Logger.comment("brands_DB:"+brands_DB.size());
		
		
		//校验返回的数据
		Logger.verifyEquals("true", call.getSuccess(), "验证success返回true");
		//查询分期乐
		//Product product=ThirdpartysyncCallService.searchFenqileSync(productId);
		//fenqilesku
		
		
		Map<String, Object> mps=new HashMap<>();
		mps.put("fenqileproduct", prodcuts_DB.get(0));
		mps.put("fenqilesku", skus_DB.get(0));
		mps.put("fenqilecategory", categorys_DB.get(0));
		mps.put("fenqilebrand", brands_DB.get(0));
		mps.put("searchFenqileSync", searchFenqileSync);
		
		return mps;
	}
	public static void checkSKUMaps(Map<String, Object> maps) throws Exception{
		
		FenqileSKUPopBean fenqileskupopBean = new FenqileSKUPopBean();
		FenqileSKUPopCall fenqileskupopCall = new FenqileSKUPopCall();
		FQLBaseParam FQLBaseParam = new FQLBaseParam();
		
		fenqileproduct fqlproduct=(fenqileproduct) maps.get("fenqileproduct");
		fenqilesku fqlesku=(fenqilesku) maps.get("fenqilesku");
		fenqilecategory fqlecategory=(fenqilecategory) maps.get("fenqilecategory");
		fenqilebrand fqlebrand=(fenqilebrand) maps.get("fenqilebrand");
		Product Product=(Product) maps.get("searchFenqileSync");
		
		//根据skuid查询全部字段
		fenqileskupopBean.setFields("sku_id,product_id,product_name,brand_id,brand_name,category_id,category_name,spec,sku_num,sku_sell_num,amount,mart_amount,sku_status,create_time,modify_time,delivery_time,sku_pic,third_sku_id,start_time,end_time,delivery_type,sku_property,wareroom_list");
		fenqileskupopBean.setSku_ids(fqlesku.getFqlSkuId());
		fenqileskupopBean.setThird_sku_ids("");
		Logger.debug(FQLOpenCallService.FenqilePopCall("fenqile.sku.detail.get", fenqileskupopBean));
		List<FenqileSkuItems> fenqilePopCallToSKUObject = FQLOpenCallService.FenqilePopCallToSKUObject("fenqile.sku.detail.get", fenqileskupopBean);
		//获取到sku列表，与数据库对比查询
		fenqilePopCallToSKUObject.forEach(b->{
			Logger.verifyEquals(b.getSku_id(), fqlesku.getFqlSkuId(),"判断skuId");
			Logger.verifyEquals(b.getProduct_id(), fqlesku.getFqlProductId(),"判断productId");
			Logger.verifyEquals(b.getBrand_id(),Product.getBrandId() ,"判断brandId");
			Logger.verifyEquals(b.getBrand_name(), Product.getBrandName(),"判断brandName");
			Logger.verifyNotEquals(b.getBrand_id(), fqlebrand.getFqlBrandId(),"错误---判断brandId");
			Logger.verifyNotEquals(b.getBrand_name(), fqlebrand.getFqlBrandName(),"错误---判断brandName");
			Logger.verifyEquals(b.getCategory_id(), fqlecategory.getFqlCategory1Id()+"|"+fqlecategory.getFqlCategory2Id()+"|"+fqlecategory.getFqlCategory3Id(),"判断catagoryId");
			Logger.verifyEquals(b.getCategory_name(), fqlecategory.getFqlCategory1Name()+"|"+fqlecategory.getFqlCategory2Name()+"|"+fqlecategory.getFqlCategory3Name(),"判断catagoryName");
//			Logger.verifyEquals(b.getSpec(), fqlecategory.get,"判断brandName");
			Logger.verifyEquals(b.getSku_num()+"", fqlesku.getYmtStock(),"判断sku_num");
			Logger.verifyEquals(b.getAmount(), fqlesku.getFqlPrice().stripTrailingZeros().toPlainString(),"判断amount");
			Logger.verifyEquals(b.getSku_status(), fqlesku.getSyncStatus()==1?"已上架":"未上架","判断sku_status");
			
			System.out.println(Product);
		});
	}
	public static void main(String args[]) {
		
	}
}
